#include <interface.h>

namespace {
  const char* drawableTitle(int idx) {
    int i = 0;
    for (auto &v : draws_) {
      if (i++ == idx) return v->title();
    }
    return "";
  }
}

SettingData::SettingData() {
  bkcolor = { 0.2f, 0.3f, 0.3f, 1.0f };
  polygonMode = GL_FILL;
  drawIndex = -1;
  lastDrawIndex = -1;
}
SettingData setting_;

extern void changeDrawable(int newIdx);
void settingApply() {
  changeDrawable(setting_.drawIndex);
  glPolygonMode(GL_FRONT_AND_BACK, setting_.polygonMode);
}

void imgui(nk_context *ctx, struct nk_rect &rc) {
  if (nk_begin(ctx, "Setting", nk_rect(rc.x, rc.y, 400, 250),
      NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
      NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) {
    
    nk_layout_row_dynamic(ctx, 20, 1);
    nk_label(ctx, "Background:", NK_TEXT_LEFT);
    nk_layout_row_dynamic(ctx, 25, 1);
    if (nk_combo_begin_color(ctx, nk_rgb_cf(setting_.bkcolor), nk_vec2(nk_widget_width(ctx),400))) {
        nk_layout_row_dynamic(ctx, 120, 1);
        setting_.bkcolor = nk_color_picker(ctx, setting_.bkcolor, NK_RGBA);
        nk_layout_row_dynamic(ctx, 25, 1);
        setting_.bkcolor.r = nk_propertyf(ctx, "#R:", 0, setting_.bkcolor.r, 1.0f, 0.01f,0.005f);
        setting_.bkcolor.g = nk_propertyf(ctx, "#G:", 0, setting_.bkcolor.g, 1.0f, 0.01f,0.005f);
        setting_.bkcolor.b = nk_propertyf(ctx, "#B:", 0, setting_.bkcolor.b, 1.0f, 0.01f,0.005f);
        setting_.bkcolor.a = nk_propertyf(ctx, "#A:", 0, setting_.bkcolor.a, 1.0f, 0.01f,0.005f);
        nk_combo_end(ctx);
    }

    nk_layout_row_dynamic(ctx, 20, 1);
    nk_label(ctx, "Polygon Mode:", NK_TEXT_LEFT);
    nk_layout_row_dynamic(ctx, 20, 2);
    if (nk_button_symbol_label(ctx, (setting_.polygonMode == GL_FILL)?NK_SYMBOL_CIRCLE_OUTLINE:NK_SYMBOL_CIRCLE_SOLID, "Fill", NK_TEXT_LEFT)) {
        setting_.polygonMode = GL_FILL;
    }
    if (nk_button_symbol_label(ctx, (setting_.polygonMode == GL_LINE)?NK_SYMBOL_CIRCLE_OUTLINE:NK_SYMBOL_CIRCLE_SOLID, "Line", NK_TEXT_LEFT)) {
        setting_.polygonMode = GL_LINE;
    }

    nk_layout_row_dynamic(ctx, 20, 1);
    nk_label(ctx, "Chapters:", NK_TEXT_LEFT);
    nk_layout_row_dynamic(ctx, 20, 1);
    if (nk_combo_begin_label(ctx, drawableTitle(setting_.drawIndex), nk_vec2(nk_widget_width(ctx), 200))) {
      nk_layout_row_dynamic(ctx, 20, 1);
      int i = 0;
      for (auto &v : draws_) {
        if (nk_combo_item_label(ctx, v->title(), NK_TEXT_LEFT))
          setting_.drawIndex = i;
        ++i;
      }
      nk_combo_end(ctx);
    }
  }
  nk_end(ctx);
};